import type { MaybeRef, UnwrapNestedRefs } from "vue";
import { computed, ref, toRef, toValue, watch } from "vue";
import { useApiFetch } from "./useApiFetch";
import { type ApiResponse } from "@/apis";
import { toUrlParams } from "@/components/utils";

export function usePageFetch<T = any>(
  url: MaybeRef<string>,
  {
    page = 1,
    pageSize = 10,
    params = {},
  }: {
    page?: MaybeRef<number>;
    pageSize?: MaybeRef<number>;
    params?: UnwrapNestedRefs<object>;
  } = {}
) {
  const count = ref(0),
    _page = toRef(page),
    _pageSize = toRef(pageSize),
    results = ref<T[]>([]);

  const result = useApiFetch(
    computed(
      () =>
        `${toRef(url).value}?${toUrlParams({
          ...toValue(params),
          pageSize: _pageSize.value,
          page: _page.value,
        })}`
    ),
    { refetch: true }
  ).json<ApiResponse<T>>();

  watch(result.data, (val) => {
    if (val?.success) {
      count.value = val.query.count;
      results.value = val.query.results;
    }
  });
  return {
    ...result,
    results,
    count,
    page: _page,
    pageSize: _pageSize,
  };
}
